package com.idcheck.rechcustoms;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import android.content.Intent;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import utils.OtherUtil;
import utils.PrefUtils;

public class AdminXianChangCunZhengActivity extends AppCompatActivity {

    private EditText companyId;
    private int adminId = 0;
    private String adminTel = "";
    private int companySeqId = 0;

    private TextView companyName;
    private CountDownTimer mTimer=null; //UI计时
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;
    private volatile long mCountSetting = 0;
    private volatile long countTimeStamp = 0;

    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;


    private boolean mVisible;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_xian_chang_cun_zheng);
        companyId = findViewById(R.id.companyId);
        companyName = findViewById(R.id.companyName);
        companyId.setEnabled(true);
        companyId.setText("");
        companyId.requestFocus();


        mVisible = true;
        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();
        companyId.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
//                //text  输入框中改变后的字符串信息
//                //start 输入框中改变后的字符串的起始位置
//                //before 输入框中改变前的字符串的位置 默认为0
//                //count 输入框中改变后的一共输入字符串的数量
//                companyName.setText("输入后字符串 [ " + text.toString() + " ] 起始光标 [ " + start + " ] 输入数量 [ " + count+" ]");

            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
//                //text  输入框中改变前的字符串信息
//                //start 输入框中改变前的字符串的起始位置
//                //count 输入框中改变前后的字符串改变数量一般为0
//                //after 输入框中改变后的字符串与起始位置的偏移量
//                System.out.println(text.toString());
//                companyName.setText("输入前字符串 [ " + text.toString() + " ]起始光标 [ " + start + " ]结束偏移量  [" + after + " ]");
            }

            @Override
            public void afterTextChanged(Editable edit) {
                String value = edit.toString();
                resetTimeStamp = System.currentTimeMillis();
                if(value.length() == 9){
                    new FetchCompanyInfoTask(value).execute();
                }
                companyName.setText("");
                findViewById(R.id.sendsubmit).setEnabled(false);
            }
        });

        adminId = Integer.parseInt(PrefUtils.getString(AdminXianChangCunZhengActivity.this, "adminid", "0"));
        findViewById(R.id.sendback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.sendsubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = adminTel;

                new FetchSendOpenTask(companySeqId,phone,adminId).execute();
            }
        });
        initTimer();
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //eventbus
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
    private void initView(){

        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;
        findViewById(R.id.sendsubmit).setEnabled(false);
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    private void resetView(){
        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            Runtime.getRuntime().exit(0); // 可选，立即退出应用
        }

    }
    private void resetViewMessage(){
        finish();
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (9999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!AdminXianChangCunZhengActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(resetTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - resetTimeStamp;
                            if(timeOut > 180000){
                                resetView();
                            }
                        }


                        if(countTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - countTimeStamp;
                            if(timeOut > 3000){
                                mCountSetting = 0;
                                countTimeStamp = 0;
                            }
                        }

                        int hours = date.getHours();
                        int minutes = date.getMinutes();
                        int seconds = date.getSeconds();


                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public static String getWeek(){
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message) {
        switch (message.what) {
            case 1500:
                EventMessageForSend(message.obj);
                break;
            case 1400:
                EventMessageForCompany(message.obj);
                break;
            default:
                EventMessageForError(message.what);
                break;

        }
    }
    private void EventMessageForCompany(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
//                findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//                companyId.setEnabled(true);
//                companyId.setText("");
//                companyId.requestFocus();
                String val = result.getJSONObject("data").getString("companyName");
                adminTel = result.getJSONObject("data").getString("contact");
                companySeqId = result.getJSONObject("data").getInt("companyId");
                companyName.setText(val);
                companyName.setTextColor(Color.BLACK);
                findViewById(R.id.sendsubmit).setEnabled(true);
                resetTimeStamp = System.currentTimeMillis();
            }else{
                //Toast.makeText(FullscreenActivity.this,result.getJSONObject("data").getString("msg"),Toast.LENGTH_LONG);
                companyName.setText(result.getString("msg"));
                companyName.setTextColor(Color.RED);
                //resetView();
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForError(int what){
        switch(what){
            case 1101:
                Toast.makeText(AdminXianChangCunZhengActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 1301:

                resetView();
                break;
            case 1401:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1501:
                Toast.makeText(AdminXianChangCunZhengActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;
            case 1701:
                Toast.makeText(AdminXianChangCunZhengActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;

        }
    }
    private void EventMessageForSend(Object obj){
        try{
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 3000);

            }else{

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.warning);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 3000);

            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("网络错误");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 3000);
        }
    }
}